"""
清洁度评分系统服务
实现基于图像分析的清洁度评分，创建多区域卫生状况的对比分析
"""
import asyncio
import logging
import cv2
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple, Any
from uuid import uuid4
import time
from collections import defaultdict, deque
import json
import math

from schemas.hygiene_management import (
    CleanlinessAssessment, CleanlinessLevel, CleanlinessConfig,
    HygieneZone, WasteAnalysisResult, HygieneIssue
)
from services.campus_environment_hygiene.waste_detection_service import waste_detection_service
from services.campus_environment_hygiene.cleanliness_standards_manager import cleanliness_standards_manager
from core.config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()


class ImageQualityAnalyzer:
    """图像质量分析器"""
    
    def analyze_surface_cleanliness(self, image: np.ndarray) -> float:
        """分析表面清洁度"""
        # 转换为灰度图
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        
        # 计算图像的清晰度（基于拉普拉斯算子）
        laplacian_var = cv2.Laplacian(gray, cv2.CV_64F).var()
        
        # 计算图像的均匀性（标准差越小越均匀）
        mean_val = np.mean(gray)
        std_val = np.std(gray)
        uniformity = 1.0 - (std_val / 255.0)
        
        # 检测边缘密度（边缘越少表示越干净）
        edges = cv2.Canny(gray, 50, 150)
        edge_density = np.sum(edges > 0) / (edges.shape[0] * edges.shape[1])
        edge_cleanliness = 1.0 - min(edge_density * 10, 1.0)
        
        # 综合评分
        surface_score = (uniformity * 0.4 + edge_cleanliness * 0.6) * 100
        
        return min(100, max(0, surface_score))
    
    def analyze_lighting_quality(self, image: np.ndarray) -> float:
        """分析光照质量"""
        # 转换为HSV色彩空间
        hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        v_channel = hsv[:, :, 2]  # 明度通道
        
        # 计算亮度分布
        mean_brightness = np.mean(v_channel)
        brightness_std = np.std(v_channel)
        
        # 理想亮度范围 (100-200)
        brightness_score = 1.0 - abs(mean_brightness - 150) / 150
        
        # 亮度均匀性
        uniformity_score = 1.0 - (brightness_std / 255.0)
        
        # 综合光照评分
        lighting_score = (brightness_score * 0.6 + uniformity_score * 0.4) * 100
        
        return min(100, max(0, lighting_score))
    
    def analyze_organization(self, image: np.ndarray) -> float:
        """分析整洁度/组织性"""
        # 转换为灰度图
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        
        # 使用霍夫变换检测直线（整齐的线条表示更好的组织性）
        edges = cv2.Canny(gray, 50, 150)
        lines = cv2.HoughLines(edges, 1, np.pi/180, threshold=100)
        
        # 计算直线密度
        line_score = 0.0
        if lines is not None:
            # 过滤相似的线条
            unique_lines = self._filter_similar_lines(lines)
            line_density = len(unique_lines) / 100  # 归一化
            line_score = min(line_density, 1.0)
        
        # 检测矩形区域（整齐的物品摆放）
        contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        rect_score = 0.0
        
        if contours:
            rectangular_contours = 0
            for contour in contours:
                # 计算轮廓的近似多边形
                epsilon = 0.02 * cv2.arcLength(contour, True)
                approx = cv2.approxPolyDP(contour, epsilon, True)
                
                # 如果是四边形且面积足够大，认为是矩形物品
                if len(approx) == 4 and cv2.contourArea(contour) > 1000:
                    rectangular_contours += 1
            
            rect_score = min(rectangular_contours / 20, 1.0)  # 归一化
        
        # 综合组织性评分
        organization_score = (line_score * 0.4 + rect_score * 0.6) * 100
        
        return min(100, max(0, organization_score))
    
    def _filter_similar_lines(self, lines: np.ndarray, angle_threshold: float = 10.0) -> List:
        """过滤相似的线条"""
        if lines is None:
            return []
        
        unique_lines = []
        
        for line in lines:
            rho, theta = line[0]
            angle = math.degrees(theta)
            
            # 检查是否与现有线条相似
            is_similar = False
            for existing_rho, existing_theta in unique_lines:
                existing_angle = math.degrees(existing_theta)
                
                if (abs(angle - existing_angle) < angle_threshold and 
                    abs(rho - existing_rho) < 50):
                    is_similar = True
                    break
            
            if not is_similar:
                unique_lines.append((rho, theta))
        
        return unique_lines
    
    def analyze_maintenance_condition(self, image: np.ndarray) -> float:
        """分析维护状况"""
        # 转换为HSV色彩空间
        hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        
        # 检测褐色/黄色区域（可能的污渍或损坏）
        # 褐色范围
        brown_lower = np.array([10, 50, 20])
        brown_upper = np.array([20, 255, 200])
        brown_mask = cv2.inRange(hsv, brown_lower, brown_upper)
        
        # 黄色污渍范围
        yellow_lower = np.array([20, 100, 100])
        yellow_upper = np.array([30, 255, 255])
        yellow_mask = cv2.inRange(hsv, yellow_lower, yellow_upper)
        
        # 计算污渍面积比例
        total_pixels = image.shape[0] * image.shape[1]
        stain_pixels = np.sum(brown_mask > 0) + np.sum(yellow_mask > 0)
        stain_ratio = stain_pixels / total_pixels
        
        # 维护状况评分（污渍越少评分越高）
        maintenance_score = (1.0 - min(stain_ratio * 20, 1.0)) * 100
        
        return min(100, max(0, maintenance_score))


class CleanlinessScorer:
    """清洁度评分器"""
    
    def __init__(self, config: CleanlinessConfig):
        self.config = config
        self.image_analyzer = ImageQualityAnalyzer()
    
    async def assess_cleanliness(
        self, 
        image: np.ndarray, 
        camera_id: str, 
        zone_id: str,
        waste_analysis: Optional[WasteAnalysisResult] = None
    ) -> CleanlinessAssessment:
        """评估清洁度"""
        assessment_factors = {}
        detected_issues = []
        recommendations = []
        
        # 1. 垃圾存在因子
        waste_score = await self._assess_waste_presence(waste_analysis, detected_issues)
        assessment_factors['waste_presence'] = waste_score
        
        # 2. 表面清洁度因子
        surface_score = self.image_analyzer.analyze_surface_cleanliness(image)
        assessment_factors['surface_cleanliness'] = surface_score
        
        # 3. 整洁度/组织性因子
        organization_score = self.image_analyzer.analyze_organization(image)
        assessment_factors['organization'] = organization_score
        
        # 4. 维护状况因子
        maintenance_score = self.image_analyzer.analyze_maintenance_condition(image)
        assessment_factors['maintenance'] = maintenance_score
        
        # 5. 光照质量因子
        lighting_score = self.image_analyzer.analyze_lighting_quality(image)
        assessment_factors['lighting'] = lighting_score
        
        # 计算加权总分
        total_score = 0.0
        for factor, score in assessment_factors.items():
            weight = self.config.weight_factors.get(factor, 0.0)
            total_score += score * weight
        
        # 确定清洁度级别
        cleanliness_level = self._determine_cleanliness_level(total_score)
        
        # 生成改进建议
        recommendations = self._generate_recommendations(assessment_factors, detected_issues)
        
        # 获取对比数据
        comparison_data = None
        if self.config.enable_comparison:
            comparison_data = await self._get_comparison_data(zone_id)
        
        assessment = CleanlinessAssessment(
            assessment_id=str(uuid4()),
            camera_id=camera_id,
            zone_id=zone_id,
            timestamp=datetime.now(),
            cleanliness_score=total_score,
            cleanliness_level=cleanliness_level,
            assessment_factors=assessment_factors,
            detected_issues=detected_issues,
            recommendations=recommendations,
            comparison_data=comparison_data
        )
        
        return assessment
    
    async def _assess_waste_presence(
        self, 
        waste_analysis: Optional[WasteAnalysisResult],
        detected_issues: List[Dict[str, Any]]
    ) -> float:
        """评估垃圾存在情况"""
        if not waste_analysis or waste_analysis.total_waste_count == 0:
            return 100.0  # 无垃圾，满分
        
        # 根据垃圾数量和面积计算评分
        waste_count = waste_analysis.total_waste_count
        waste_area = waste_analysis.total_waste_area
        
        # 垃圾数量惩罚
        count_penalty = min(waste_count * 10, 80)  # 每个垃圾扣10分，最多扣80分
        
        # 垃圾面积惩罚
        area_penalty = min(waste_area / 1000, 20)  # 面积惩罚，最多扣20分
        
        # 记录检测到的问题
        for detection in waste_analysis.detections:
            issue = {
                'type': 'waste',
                'waste_type': detection.waste_type.value,
                'severity': 'high' if detection.area > 5000 else 'medium',
                'location': detection.location,
                'confidence': detection.confidence
            }
            detected_issues.append(issue)
        
        waste_score = max(0, 100 - count_penalty - area_penalty)
        return waste_score
    
    def _determine_cleanliness_level(self, score: float) -> CleanlinessLevel:
        """确定清洁度级别"""
        for level, (min_score, max_score) in self.config.score_thresholds.items():
            if min_score <= score <= max_score:
                return CleanlinessLevel(level)
        
        return CleanlinessLevel.POOR
    
    def _generate_recommendations(
        self, 
        assessment_factors: Dict[str, float],
        detected_issues: List[Dict[str, Any]]
    ) -> List[str]:
        """生成改进建议"""
        recommendations = []
        
        # 基于评估因子生成建议
        if assessment_factors.get('waste_presence', 100) < 80:
            recommendations.append("需要清理垃圾，建议增加垃圾桶数量")
        
        if assessment_factors.get('surface_cleanliness', 100) < 70:
            recommendations.append("表面需要深度清洁，建议使用专业清洁剂")
        
        if assessment_factors.get('organization', 100) < 70:
            recommendations.append("物品摆放需要整理，建议制定物品摆放标准")
        
        if assessment_factors.get('maintenance', 100) < 70:
            recommendations.append("发现维护问题，建议安排维修检查")
        
        if assessment_factors.get('lighting', 100) < 60:
            recommendations.append("光照条件需要改善，建议检查照明设备")
        
        # 基于检测到的问题生成具体建议
        waste_types = set()
        for issue in detected_issues:
            if issue['type'] == 'waste':
                waste_types.add(issue['waste_type'])
        
        if 'organic' in waste_types:
            recommendations.append("发现有机垃圾，建议及时清理以防异味")
        
        if 'hazardous' in waste_types:
            recommendations.append("发现有害垃圾，需要专业处理")
        
        return recommendations
    
    async def _get_comparison_data(self, zone_id: str) -> Dict[str, Any]:
        """获取对比数据"""
        # 这里应该从历史数据中获取对比信息
        # 为了演示，返回模拟数据
        return {
            'previous_week_average': 78.5,
            'previous_month_average': 82.1,
            'trend': 'improving',
            'rank_among_zones': 3,
            'total_zones': 10
        }


class CleanlinessAssessmentService:
    """清洁度评估服务"""
    
    def __init__(self):
        self.config = CleanlinessConfig()
        self.scorer = CleanlinessScorer(self.config)
        
        self.assessments: List[CleanlinessAssessment] = []
        self.zones: Dict[str, HygieneZone] = {}
        
        # 服务状态
        self._running = False
        self._assessment_task = None
        self.assessment_interval = 300.0  # 5分钟评估一次
        
        # 统计信息
        self.stats = {
            'total_assessments': 0,
            'average_cleanliness_score': 0.0,
            'zone_rankings': {},
            'improvement_trends': {}
        }
        
        # 初始化默认区域
        self._initialize_default_zones()
    
    def _initialize_default_zones(self):
        """初始化默认区域"""
        default_zones = [
            HygieneZone(
                zone_id="classroom_101",
                zone_name="教室101",
                zone_type="classroom",
                coordinates=[(0, 0), (100, 0), (100, 80), (0, 80)],
                area_sqm=80.0,
                cleaning_frequency="daily",
                cleanliness_standard=85.0
            ),
            HygieneZone(
                zone_id="hallway_1",
                zone_name="走廊1",
                zone_type="hallway",
                coordinates=[(0, 0), (200, 0), (200, 30), (0, 30)],
                area_sqm=60.0,
                cleaning_frequency="twice_daily",
                cleanliness_standard=80.0
            ),
            HygieneZone(
                zone_id="restroom_1",
                zone_name="洗手间1",
                zone_type="restroom",
                coordinates=[(0, 0), (50, 0), (50, 40), (0, 40)],
                area_sqm=20.0,
                cleaning_frequency="hourly",
                cleanliness_standard=90.0
            )
        ]
        
        for zone in default_zones:
            self.zones[zone.zone_id] = zone
    
    async def start_service(self):
        """启动服务"""
        if self._running:
            return
        
        self._running = True
        self._assessment_task = asyncio.create_task(self._assessment_loop())
        logger.info("Cleanliness assessment service started")
    
    async def stop_service(self):
        """停止服务"""
        self._running = False
        if self._assessment_task:
            self._assessment_task.cancel()
            try:
                await self._assessment_task
            except asyncio.CancelledError:
                pass
        logger.info("Cleanliness assessment service stopped")
    
    async def _assessment_loop(self):
        """评估循环"""
        while self._running:
            try:
                await self._periodic_assessment()
                await asyncio.sleep(self.assessment_interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Error in cleanliness assessment loop: {e}")
                await asyncio.sleep(30.0)
    
    async def _periodic_assessment(self):
        """周期性评估"""
        # 清理过期的评估结果
        cutoff_time = datetime.now() - timedelta(days=30)  # 保留30天
        self.assessments = [
            assessment for assessment in self.assessments 
            if assessment.timestamp > cutoff_time
        ]
        
        # 更新区域清洁度
        await self._update_zone_cleanliness()
        
        # 更新统计信息
        self._update_statistics()
    
    async def _update_zone_cleanliness(self):
        """更新区域清洁度"""
        for zone_id, zone in self.zones.items():
            # 获取最近的评估结果
            recent_assessments = [
                assessment for assessment in self.assessments
                if (assessment.zone_id == zone_id and 
                    assessment.timestamp > datetime.now() - timedelta(hours=24))
            ]
            
            if recent_assessments:
                # 计算平均清洁度
                avg_cleanliness = sum(a.cleanliness_score for a in recent_assessments) / len(recent_assessments)
                zone.current_cleanliness = avg_cleanliness
    
    def _update_statistics(self):
        """更新统计信息"""
        if not self.assessments:
            return
        
        # 计算总体统计
        self.stats['total_assessments'] = len(self.assessments)
        
        recent_assessments = [
            a for a in self.assessments 
            if a.timestamp > datetime.now() - timedelta(days=7)
        ]
        
        if recent_assessments:
            self.stats['average_cleanliness_score'] = sum(
                a.cleanliness_score for a in recent_assessments
            ) / len(recent_assessments)
        
        # 计算区域排名
        zone_scores = defaultdict(list)
        for assessment in recent_assessments:
            zone_scores[assessment.zone_id].append(assessment.cleanliness_score)
        
        zone_averages = {
            zone_id: sum(scores) / len(scores)
            for zone_id, scores in zone_scores.items()
        }
        
        # 按评分排序
        sorted_zones = sorted(zone_averages.items(), key=lambda x: x[1], reverse=True)
        self.stats['zone_rankings'] = {
            zone_id: rank + 1 
            for rank, (zone_id, score) in enumerate(sorted_zones)
        }
    
    async def assess_image_cleanliness(
        self, 
        image: np.ndarray, 
        camera_id: str, 
        zone_id: str
    ) -> CleanlinessAssessment:
        """评估图像清洁度"""
        try:
            # 获取区域的清洁标准
            zone_config = cleanliness_standards_manager.get_zone_config(zone_id)
            
            # 使用区域特定的配置创建评分器
            zone_scorer = CleanlinessScorer(zone_config)
            
            # 先进行垃圾检测
            waste_analysis = await waste_detection_service.analyze_waste(image, camera_id, zone_id)
            
            # 进行清洁度评估
            assessment = await zone_scorer.assess_cleanliness(
                image, camera_id, zone_id, waste_analysis
            )
            
            # 存储评估结果
            self.assessments.append(assessment)
            
            # 保持最近1000个评估结果
            if len(self.assessments) > 1000:
                self.assessments = self.assessments[-1000:]
            
            # 更新区域信息
            if zone_id in self.zones:
                zone = self.zones[zone_id]
                zone.current_cleanliness = assessment.cleanliness_score
                zone.last_cleaned = datetime.now()  # 假设评估时进行了清洁
            
            return assessment
            
        except Exception as e:
            logger.error(f"Cleanliness assessment failed: {e}")
            raise
    
    async def get_assessments(
        self,
        camera_id: Optional[str] = None,
        zone_id: Optional[str] = None,
        cleanliness_level: Optional[CleanlinessLevel] = None,
        start_time: Optional[datetime] = None,
        end_time: Optional[datetime] = None,
        limit: int = 100
    ) -> List[CleanlinessAssessment]:
        """获取评估结果"""
        assessments = self.assessments
        
        # 过滤条件
        if camera_id:
            assessments = [a for a in assessments if a.camera_id == camera_id]
        
        if zone_id:
            assessments = [a for a in assessments if a.zone_id == zone_id]
        
        if cleanliness_level:
            assessments = [a for a in assessments if a.cleanliness_level == cleanliness_level]
        
        if start_time:
            assessments = [a for a in assessments if a.timestamp >= start_time]
        
        if end_time:
            assessments = [a for a in assessments if a.timestamp <= end_time]
        
        # 按时间倒序排列
        assessments.sort(key=lambda x: x.timestamp, reverse=True)
        
        return assessments[:limit]
    
    async def compare_zones(self, zone_ids: List[str], time_range: timedelta = timedelta(days=7)) -> Dict[str, Any]:
        """对比多个区域的卫生状况"""
        end_time = datetime.now()
        start_time = end_time - time_range
        
        comparison_data = {}
        
        for zone_id in zone_ids:
            zone_assessments = [
                a for a in self.assessments
                if (a.zone_id == zone_id and start_time <= a.timestamp <= end_time)
            ]
            
            if zone_assessments:
                scores = [a.cleanliness_score for a in zone_assessments]
                comparison_data[zone_id] = {
                    'zone_name': self.zones.get(zone_id, {}).zone_name if zone_id in self.zones else zone_id,
                    'average_score': sum(scores) / len(scores),
                    'max_score': max(scores),
                    'min_score': min(scores),
                    'assessment_count': len(zone_assessments),
                    'trend': self._calculate_trend(zone_assessments),
                    'current_level': zone_assessments[0].cleanliness_level.value if zone_assessments else 'unknown'
                }
            else:
                comparison_data[zone_id] = {
                    'zone_name': self.zones.get(zone_id, {}).zone_name if zone_id in self.zones else zone_id,
                    'average_score': 0,
                    'assessment_count': 0,
                    'trend': 'no_data'
                }
        
        # 排序
        sorted_zones = sorted(
            comparison_data.items(), 
            key=lambda x: x[1]['average_score'], 
            reverse=True
        )
        
        return {
            'time_range': {
                'start': start_time.isoformat(),
                'end': end_time.isoformat()
            },
            'zone_comparison': dict(sorted_zones),
            'best_zone': sorted_zones[0][0] if sorted_zones else None,
            'worst_zone': sorted_zones[-1][0] if sorted_zones else None,
            'overall_average': sum(data['average_score'] for data in comparison_data.values()) / len(comparison_data) if comparison_data else 0
        }
    
    def _calculate_trend(self, assessments: List[CleanlinessAssessment]) -> str:
        """计算趋势"""
        if len(assessments) < 2:
            return 'insufficient_data'
        
        # 按时间排序
        sorted_assessments = sorted(assessments, key=lambda x: x.timestamp)
        
        # 计算前半部分和后半部分的平均分
        mid_point = len(sorted_assessments) // 2
        first_half_avg = sum(a.cleanliness_score for a in sorted_assessments[:mid_point]) / mid_point
        second_half_avg = sum(a.cleanliness_score for a in sorted_assessments[mid_point:]) / (len(sorted_assessments) - mid_point)
        
        diff = second_half_avg - first_half_avg
        
        if diff > 5:
            return 'improving'
        elif diff < -5:
            return 'declining'
        else:
            return 'stable'
    
    def add_zone(self, zone: HygieneZone):
        """添加区域"""
        self.zones[zone.zone_id] = zone
        logger.info(f"Added hygiene zone: {zone.zone_id}")
    
    def get_zones(self) -> List[HygieneZone]:
        """获取所有区域"""
        return list(self.zones.values())
    
    def get_zone(self, zone_id: str) -> Optional[HygieneZone]:
        """获取指定区域"""
        return self.zones.get(zone_id)
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取统计信息"""
        return self.stats.copy()
    
    def update_config(self, config: CleanlinessConfig):
        """更新配置"""
        self.config = config
        self.scorer = CleanlinessScorer(config)
        logger.info("Cleanliness assessment configuration updated")
    
    def get_config(self) -> CleanlinessConfig:
        """获取配置"""
        return self.config
    
    # 清洁标准管理接口
    def create_cleanliness_standard(self, standard_data: Dict[str, Any]) -> str:
        """创建清洁标准"""
        from services.campus_environment_hygiene.cleanliness_standards_manager import CleanlinessStandard
        
        standard = CleanlinessStandard(
            standard_id=standard_data.get('standard_id', str(uuid4())),
            name=standard_data['name'],
            description=standard_data['description'],
            zone_type=standard_data['zone_type'],
            score_thresholds=standard_data['score_thresholds'],
            weight_factors=standard_data['weight_factors'],
            cleaning_frequency=standard_data['cleaning_frequency'],
            special_requirements=standard_data.get('special_requirements', [])
        )
        
        return cleanliness_standards_manager.create_standard(standard)
    
    def update_cleanliness_standard(self, standard_id: str, updates: Dict[str, Any]) -> bool:
        """更新清洁标准"""
        return cleanliness_standards_manager.update_standard(standard_id, updates)
    
    def delete_cleanliness_standard(self, standard_id: str) -> bool:
        """删除清洁标准"""
        return cleanliness_standards_manager.delete_standard(standard_id)
    
    def get_cleanliness_standard(self, standard_id: str) -> Optional[Dict[str, Any]]:
        """获取清洁标准"""
        standard = cleanliness_standards_manager.get_standard(standard_id)
        return standard.to_dict() if standard else None
    
    def get_all_cleanliness_standards(self) -> List[Dict[str, Any]]:
        """获取所有清洁标准"""
        standards = cleanliness_standards_manager.get_all_standards()
        return [standard.to_dict() for standard in standards]
    
    def get_standards_by_zone_type(self, zone_type: str) -> List[Dict[str, Any]]:
        """根据区域类型获取清洁标准"""
        standards = cleanliness_standards_manager.get_standards_by_zone_type(zone_type)
        return [standard.to_dict() for standard in standards]
    
    def assign_standard_to_zone(self, zone_id: str, standard_id: str) -> bool:
        """为区域分配清洁标准"""
        return cleanliness_standards_manager.assign_standard_to_zone(zone_id, standard_id)
    
    def get_zone_cleanliness_standard(self, zone_id: str) -> Optional[Dict[str, Any]]:
        """获取区域的清洁标准"""
        standard = cleanliness_standards_manager.get_zone_standard(zone_id)
        return standard.to_dict() if standard else None
    
    def validate_cleanliness_standard(self, standard_data: Dict[str, Any]) -> List[str]:
        """验证清洁标准"""
        from services.campus_environment_hygiene.cleanliness_standards_manager import CleanlinessStandard
        
        try:
            standard = CleanlinessStandard(
                standard_id=standard_data.get('standard_id', 'temp'),
                name=standard_data['name'],
                description=standard_data['description'],
                zone_type=standard_data['zone_type'],
                score_thresholds=standard_data['score_thresholds'],
                weight_factors=standard_data['weight_factors'],
                cleaning_frequency=standard_data['cleaning_frequency'],
                special_requirements=standard_data.get('special_requirements', [])
            )
            
            return cleanliness_standards_manager.validate_standard(standard)
        
        except Exception as e:
            return [f"Invalid standard data: {str(e)}"]
    
    def get_standards_statistics(self) -> Dict[str, Any]:
        """获取清洁标准统计信息"""
        return cleanliness_standards_manager.get_statistics()
    
    def export_cleanliness_standards(self, file_path: str) -> bool:
        """导出清洁标准"""
        return cleanliness_standards_manager.export_standards(file_path)
    
    def import_cleanliness_standards(self, file_path: str, overwrite: bool = False) -> Dict[str, Any]:
        """导入清洁标准"""
        return cleanliness_standards_manager.import_standards(file_path, overwrite)
    
    async def assess_zone_compliance(self, zone_id: str, days: int = 7) -> Dict[str, Any]:
        """评估区域合规性"""
        # 获取区域标准
        standard = cleanliness_standards_manager.get_zone_standard(zone_id)
        if not standard:
            return {
                'zone_id': zone_id,
                'compliance_status': 'no_standard',
                'message': 'No cleanliness standard assigned to this zone'
            }
        
        # 获取最近的评估结果
        end_time = datetime.now()
        start_time = end_time - timedelta(days=days)
        
        recent_assessments = [
            a for a in self.assessments
            if (a.zone_id == zone_id and start_time <= a.timestamp <= end_time)
        ]
        
        if not recent_assessments:
            return {
                'zone_id': zone_id,
                'compliance_status': 'no_data',
                'message': 'No assessment data available for the specified period'
            }
        
        # 计算合规性
        total_assessments = len(recent_assessments)
        compliant_assessments = 0
        
        # 获取标准的最低要求（good级别的最低分）
        min_acceptable_score = standard.score_thresholds.get('good', (80, 89))[0]
        
        for assessment in recent_assessments:
            if assessment.cleanliness_score >= min_acceptable_score:
                compliant_assessments += 1
        
        compliance_rate = compliant_assessments / total_assessments
        
        # 计算平均分
        average_score = sum(a.cleanliness_score for a in recent_assessments) / total_assessments
        
        # 确定合规状态
        if compliance_rate >= 0.9:
            compliance_status = 'excellent'
        elif compliance_rate >= 0.8:
            compliance_status = 'good'
        elif compliance_rate >= 0.7:
            compliance_status = 'acceptable'
        else:
            compliance_status = 'poor'
        
        return {
            'zone_id': zone_id,
            'zone_name': self.zones.get(zone_id, {}).zone_name if zone_id in self.zones else zone_id,
            'standard_name': standard.name,
            'compliance_status': compliance_status,
            'compliance_rate': compliance_rate,
            'average_score': average_score,
            'min_acceptable_score': min_acceptable_score,
            'total_assessments': total_assessments,
            'compliant_assessments': compliant_assessments,
            'assessment_period_days': days,
            'recommendations': self._generate_compliance_recommendations(
                compliance_rate, average_score, min_acceptable_score
            )
        }
    
    def _generate_compliance_recommendations(
        self, 
        compliance_rate: float, 
        average_score: float, 
        min_acceptable_score: float
    ) -> List[str]:
        """生成合规性改进建议"""
        recommendations = []
        
        if compliance_rate < 0.7:
            recommendations.append("合规率过低，需要立即采取改进措施")
            recommendations.append("建议增加清洁频率")
            recommendations.append("加强清洁人员培训")
        
        if average_score < min_acceptable_score:
            recommendations.append(f"平均分({average_score:.1f})低于标准要求({min_acceptable_score})")
            recommendations.append("建议检查清洁流程和标准执行情况")
        
        if compliance_rate < 0.8:
            recommendations.append("建议建立定期检查机制")
            recommendations.append("考虑调整清洁标准或增加资源投入")
        
        if not recommendations:
            recommendations.append("当前合规性良好，继续保持")
        
        return recommendations
    
    async def process_video_frame(self, frame: np.ndarray, metadata: Dict[str, Any] = None) -> Dict[str, Any]:
        """处理视频帧进行清洁度评估"""
        try:
            camera_id = metadata.get('camera_id', 'unknown') if metadata else 'unknown'
            zone_id = metadata.get('zone_id', 'default_zone') if metadata else 'default_zone'
            frame_timestamp = datetime.fromisoformat(metadata.get('frame_timestamp')) if metadata and metadata.get('frame_timestamp') else datetime.now()
            
            # 进行清洁度评估
            assessment = await self.assess_image_cleanliness(frame, camera_id, zone_id)
            
            # 获取区域信息
            zone_info = self.get_zone(zone_id)
            
            return {
                "algorithm": "cleanliness_assessment",
                "camera_id": camera_id,
                "frame_timestamp": frame_timestamp.isoformat(),
                "processing_timestamp": datetime.now().isoformat(),
                "results": {
                    "cleanliness_score": assessment.cleanliness_score,
                    "cleanliness_level": assessment.cleanliness_level.value,
                    "assessment_factors": assessment.assessment_factors,
                    "detected_issues": assessment.detected_issues,
                    "recommendations": assessment.recommendations,
                    "zone_info": {
                        "zone_id": zone_id,
                        "zone_name": zone_info.zone_name if zone_info else zone_id,
                        "zone_type": zone_info.zone_type if zone_info else "unknown",
                        "cleanliness_standard": zone_info.cleanliness_standard if zone_info else 80.0,
                        "current_cleanliness": zone_info.current_cleanliness if zone_info else assessment.cleanliness_score
                    },
                    "comparison_data": assessment.comparison_data
                },
                "confidence": 0.85,
                "processing_time": 0.2
            }
            
        except Exception as e:
            logger.error(f"清洁度评估处理视频帧失败: {e}")
            return {
                "algorithm": "cleanliness_assessment",
                "camera_id": metadata.get('camera_id', 'unknown') if metadata else 'unknown',
                "error": str(e),
                "processing_timestamp": datetime.now().isoformat()
            }


# 全局清洁度评估服务实例
cleanliness_assessment_service = CleanlinessAssessmentService()